import 'package:dotted_border/dotted_border.dart';
import 'package:flustars/flustars.dart';
import 'package:flutter/material.dart';
import 'package:flutter_lang/flutter_lang.dart';
import 'package:flutter_theme/theme.dart';
import 'package:flutter_theme/theme_utils.dart';
import 'package:lifecycle_monitor/lifecycle_monitor.dart';
import 'package:oktoast/oktoast.dart';
import 'package:route_manager/wx_navigator.dart';
import 'package:wallet_authentication/PIN/models/wallet_info_model.dart';
import 'package:wallet_authentication/module_config.dart';
import 'package:wallet_authentication/utils/aes_util.dart';

class VerifyMnemonicWalletScreen extends StatefulWidget {
  final String mnemonicString;

  const VerifyMnemonicWalletScreen({@required this.mnemonicString, Key key})
      : super(key: key);

  @override
  _VerifyMnemonicWalletScreenState createState() =>
      _VerifyMnemonicWalletScreenState();
}

class _VerifyMnemonicWalletScreenState
    extends State<VerifyMnemonicWalletScreen> {
  List<String> mnemonicPutInList = [
    "1",
    "2",
    "3",
    "4",
    "5",
    "6",
    "7",
    "8",
    "9",
    "10",
    "11",
    "12"
  ];
  List<String> mnemonicList = [];
  List<String> mnemonicVerifyList = [];

  @override
  void initState() {
    super.initState();
    mnemonicList = widget.mnemonicString.split(" ");

    for (int i = 0; i < mnemonicList.length; i++) {
      mnemonicVerifyList.add(mnemonicList[i]);
    }

    mnemonicVerifyList.shuffle();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: WXTheme.$c("authentication_header_background"),
        centerTitle: true,
        elevation: 0,
        title: Text(
            "${WXLang.$t("authentication_verify_mnemonic", package: ModuleConfig.moduleName)}"),
        brightness: Brightness.dark,
        // backgroundColor: Color(0xbb000000),
      ),
//      FIXME: 这种长篇的代码需要分离
      body: Container(
        child: Column(
          children: <Widget>[
            Container(
              padding: EdgeInsets.all(10),
              child: Column(
                children: <Widget>[
                  Container(
                    margin: EdgeInsets.fromLTRB(20, 5, 20, 0),
                    child: Text(
                        "${WXLang.$t("authentication_verify_mnemonic_info", package: ModuleConfig.moduleName)}"),
                  ),
                  SizedBox(
                    height: 8,
                  ),
                  Container(
                    decoration: BoxDecoration(
                        color: WXTheme.$c("authentication_list_item_color"),
                        border: Border.all(
                            color:
                                WXTheme.$c("authentication_common_text_title"),
                            width: 1.0),
                        borderRadius: BorderRadius.circular(8)),
                    margin: EdgeInsets.symmetric(
                      vertical: 10,
                    ),
                    padding: EdgeInsets.symmetric(vertical: 13, horizontal: 10),
                    child: _inputShowGrid(),
                  ),
                  Offstage(
                    offstage: mnemonicVerifyList.length == 0 ? true : false,
                    child: Container(
                      decoration: BoxDecoration(
                          color: WXTheme.$c("authentication_list_item_color"),
                          border: Border.all(
                              color: WXTheme.$c(
                                  "authentication_common_text_title"),
                              width: 1.0),
                          borderRadius: BorderRadius.circular(8)),
                      margin: EdgeInsets.symmetric(
                        vertical: 12,
                      ),
                      padding:
                          EdgeInsets.symmetric(vertical: 13, horizontal: 10),
                      child: _verifiedGrid(),
                    ),
                  ),
                ],
              ),
            ),
            Expanded(
              child: SizedBox(),
            ),
            Container(
              padding: EdgeInsets.fromLTRB(20, 10, 20, 25),
              child: Container(
                child: MaterialButton(
                  padding: EdgeInsets.symmetric(vertical: 15),
                  minWidth: double.infinity,
                  color: Colors.blue,
                  disabledColor: Color(0xFFD6D6D6),
                  child: Text(
                    "${WXLang.$t("authentication_backup_mnemonic", package: ModuleConfig.moduleName)}",
                    style: TextStyle(
                        color: Color(0xDDFFFFFF),
                        fontWeight: FontWeight.w800,
                        letterSpacing: 1,
                        fontSize: 14),
                  ),
//                  FIXME: 可以单独成方法呀
                  onPressed: mnemonicVerifyList.length == 0
                      ? () {
                          if (_isEqual(mnemonicPutInList, mnemonicList)) {
                            // PinCode保存操作 | 保存钱包名称
                            WalletInfo.savePinCodeName();
                            WalletInfo.saveWalletName();

                            //跳转前先保存bool变量和助记词
                            SpUtil.putBool("verified_mnemonic", true);
                            SpUtil.putString("mnemonic_list",
                                AESUtil.encryptString(widget.mnemonicString));

                            /// 注册息屏逻辑
                            StateObserver().registerObserver();

                            // 成功后跳转到首页
                            WXNavigator.pushNamedAndRemoveUntil(
                                "/wallet_home", (route) => false,
                                context: context, moduleName: "wallet_home");
                          } else {
                            showToast(
                                "${WXLang.$t("authentication_verify_failed", package: ModuleConfig.moduleName)}");
                          }
                        }
                      : null,
                ),
              ),
            )
          ],
        ),
      ),
    );
  }

  Widget _inputShowGrid() {
    return GridView.count(
        physics: NeverScrollableScrollPhysics(),
        mainAxisSpacing: 10,
        crossAxisSpacing: 10,
        shrinkWrap: true,
        childAspectRatio: 2.2,
        crossAxisCount: 4,
        children: List.generate(12, (i) {
          return InkWell(
            onTap: () {
              //点击数字不做操作
              if (_isDigit(i)) {
                return;
              }

              //点击单词
              setState(() {
                mnemonicVerifyList.add(mnemonicPutInList[i]);
                mnemonicPutInList[i] = (i + 1).toString();
              });
            },
            child: _containerWidget(i),
          );
        }));
  }

  Widget _containerWidget(int index) {
    if (_isDigit(index)) {
      return Container(
          decoration: BoxDecoration(
            color: WXTheme.$c("authentication_mnemonic_grid_item_color"),
            borderRadius: BorderRadius.circular(2),
          ),
          padding: EdgeInsets.all(1),
          child: DottedBorder(
            color: WXTheme.$c("authentication_divider_color"),
            child: Center(
              child: Text(
                '${mnemonicPutInList[index]}',
                style: TextStyle(
                    color: WXTheme.$c("authentication_common_text_title"),
                    fontSize: 12),
              ),
            ),
            // ),
          ));
    } else {
      return Container(
        decoration: BoxDecoration(
            color: WXTheme.$c("authentication_mnemonic_grid_item_color"),
            borderRadius: BorderRadius.circular(2),
            border: Border.all(color: Color(0x08000000))),
        padding: EdgeInsets.all(1),
        child: Center(
          child: Text(
            '${mnemonicPutInList[index]}',
            style: TextStyle(
                color: WXTheme.$c("authentication_common_text_title"),
                fontSize: 12),
          ),
        ),
      );
    }
  }

  Widget _verifiedGrid() {
    return GridView.count(
        physics: NeverScrollableScrollPhysics(),
        mainAxisSpacing: 10,
        crossAxisSpacing: 10,
        shrinkWrap: true,
        childAspectRatio: 2.2,
        crossAxisCount: 4,
        children: List.generate(mnemonicVerifyList.length, (i) {
          return InkWell(
            onTap: () {
              setState(() {
                mnemonicPutInList[_firstDigitIndex()] = mnemonicVerifyList[i];
                mnemonicVerifyList.removeAt(i);
              });
            },
            child: Container(
              decoration: BoxDecoration(
                  color: WXTheme.$c("authentication_mnemonic_grid_item_color"),
                  borderRadius: BorderRadius.circular(2),
                  border: Border.all(
                      color: WXTheme.$c("authentication_divider_color"))),
              padding: EdgeInsets.all(1),
              child: Center(
                child: Text(
                  '${mnemonicVerifyList[i]}',
                  style: TextStyle(
                      color: WXTheme.$c("authentication_list_item_text"),
                      fontSize: 12),
                ),
              ),
            ),
          );
        }));
  }

  bool _isDigit(int index) {
    if (int.tryParse(mnemonicPutInList[index]) != null) {
      return true;
    }
    return false;
  }

  int _firstDigitIndex() {
    for (int i = 0; i < mnemonicPutInList.length; i++) {
      if (_isDigit(i)) {
        return i;
      }
    }

    return -1;
  }

  bool _isEqual(List<String> list1, List<String> list2) {
    if (list1 == list2) {
      return true;
    }
    if (list1 == null || list2 == null) {
      return false;
    }
    if (list1.length != list2.length) {
      return false;
    }
    for (int i = 0; i < list1.length; i++) {
      if (list1[i] != list2[i]) {
        return false;
      }
    }

    return true;
  }
}
